package com.example.teaching_server.repository;

import com.example.teaching_server.entity.ActivityCheckinEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.util.List;

/**
 * 活动打卡记录数据访问层
 */
@Repository
public interface ActivityCheckinRepository extends JpaRepository<ActivityCheckinEntity, Long> {

    @Query("SELECT c FROM ActivityCheckinEntity c WHERE c.userId = :userId AND c.checkDate = :date")
    List<ActivityCheckinEntity> findByUserIdAndDate(@Param("userId") Long userId, @Param("date") LocalDate date);

    @Query("SELECT c FROM ActivityCheckinEntity c WHERE c.userId = :userId AND c.activityId = :activityId")
    List<ActivityCheckinEntity> findByUserIdAndActivityId(@Param("userId") Long userId, @Param("activityId") Long activityId);

    @Query("SELECT COUNT(c) > 0 FROM ActivityCheckinEntity c WHERE c.userId = :userId AND c.activityId = :activityId AND c.checkDate = :date")
    boolean existsByUserIdAndActivityIdAndCheckDate(@Param("userId") Long userId,
                                                    @Param("activityId") Long activityId,
                                                    @Param("date") LocalDate date);

    @Query(value = "SELECT activity_id FROM activity_participants WHERE user_id = :userId",
            nativeQuery = true)
    List<Long> findJoinedActivityIds(@Param("userId") Long userId);

    @Query("SELECT c FROM ActivityCheckinEntity c WHERE c.userId = :userId AND c.checkDate = :date AND c.activityId IN :activityIds")
    List<ActivityCheckinEntity> findByUserIdAndDateAndActivityIds(
            @Param("userId") Long userId,
            @Param("date") LocalDate date,
            @Param("activityIds") List<Long> activityIds);
}
